import React, { Component } from 'react'
import FlexGrow from './List'
import Actions from '../../actions';
import { Pagination, Icon, Modal, Tag } from 'antd';
import { fetchData } from '../../components/AjaxConsumer'
import styles from './index.scss'

export default class ListBox extends Component {

    constructor(props) {
        super(props);
        this.pageNext = this.pageNext.bind(this);
        this.getListData = this.getListData.bind(this);
        this.hiddenBox = this.hiddenBox.bind(this);
        this.state = {
            loading: true,  //loading 加载

            indexList: [],//当前渲染的页面数据
            current: 1, //当前页码
            pageSize: 20, //每页显示的条数
            totalPage: 0,//总页数
            totalCount: 0, //总记录数
            formBoxStyleMin: '', //formbox的动画移动标识
            formBoxStyleHeight: '', //formbox的动画移动宽度
            conditonData: {}, //查询条件
            order: null,
            showTotalAmount: false,  //是够显示尾行合计
            totalAmount: {}, //尾末合计行数据
            url:props.url
        };
        this.selectedRowsObj = [];
        this.permissions = this.localPerms(); //获取本地权限
    }

    componentWillMount() {
        // this.getListData();
        if(this.props.unLoading != undefined){
        this.getloading();
        }else{
            this.getListData();
        }
    }
    componentWillReceiveProps(nextProps) {
        const { url } = this.state
        const newurl = nextProps.url.toString()
        if (url.toString() !== newurl) {
          this.setState({
            url: nextProps.url,
          },()=>{
            this.getListData();
            //console.log("+++++++++++++++++++++++++++++++++")
          })
        }
      }
    localPerms = () => {
        let perms = window.localStorage.getItem("permissions");
        let arr = [];
        if(perms){
            if (perms.indexOf(",") != -1) {
                return perms.split(",");
            } else {
                arr[0] = perms;
                return arr;
            }
        }
    }

    rowHandles = (strHandles) => {
        if (strHandles === "export") {
            this.props.rowHandles("export", this.state.conditonData);
        } else if (strHandles === "exportPdf") {
            this.props.rowHandles("exportPdf", this.state.conditonData);
        } else {
            this.props.rowHandles(strHandles, this.selectedRowsObj);
        }
    };
    selectedRowsObjHandles = (rowsObj) => {
        this.selectedRowsObj = rowsObj;
    };
    getloading =() => {
        this.setState({
            loading: false,
            indexList: [], //当前页面数据
            totalCount: 0, //总记录数
           // order: resData.data.order,
            totalPage: 1,//总页数
            current: 1, //当前页码
            pageSize: 20, //每页显示的条数
           // totalAmount: tempAmount  //尾行合计数据
        },() => console.log('loading',this.state.loading));
      
    }

    //获取数据
    getListData(num, pageSize, conditonData) {
        if (typeof (num) == "undefined" || num == null || num.length == 0) {
            num = this.state.current;
        }
        if (typeof (pageSize) == "undefined" || pageSize == null || pageSize.length == 0) {
            pageSize = this.state.pageSize;
        }
        if (typeof (conditonData) == "undefined" || conditonData == null || conditonData.length == 0) {
            conditonData = this.state.conditonData
        } else {
            //点击搜索，有查询条件，分页要重新从第一页开始
            num = 1;
            //保存查询条件
            this.setState({
                conditonData: conditonData
            });
        }

        //let conData = { page: num, rows: pageSize, condition: conditonData };
        //$.ajax({url: this.props.url,type: 'post',contentType:'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify(conData) })
        // $.ajax({url: this.props.url,type: 'post', dataType: 'json', data: { page: num, rows: pageSize, ...conditonData } })
        //     .done(function (resData, status, xhr) {
        //         //console.log("getList返回数据：\n",JSON.stringify(resData, null, 4));
        //         if(resData.code == "1"){
        //             this.setState({
        //                 loading: false,
        //                 indexList: resData.data.records, //当前页面数据
        //                 totalCount: resData.data.totalCount, //总记录数
        //                 totalPage: resData.data.totalPage,//总页数
        //                 current: num, //当前页码
        //                 pageSize: pageSize, //每页显示的条数
        //             });
        //         }else{
        //             console.log("请求数据错误：", resData.message);
        //         }
        //     }.bind(this));

        const options = {
            url: this.props.url,
            type: 'post',
            condition: {
                page: num,
                rows: pageSize,
                ...conditonData
            }
        };
        fetchData(this, options, (resData) => {
            if (resData.code == "1") {

                let tempAmount = {};
                if (resData.data.order) { //合计有数据

                    let orderstr = resData.data.order;
                    // let patt = /(\w+)(?:=([^;]*))?/g;
                    // let regarr = orderstr.match(patt);
                    tempAmount = JSON.parse(orderstr);

                    this.setState({
                        showTotalAmount: true
                    })
                }

                this.setState({
                    loading: false,
                    indexList: resData.data.records, //当前页面数据
                    totalCount: resData.data.totalCount, //总记录数
                    order: resData.data.order,
                    totalPage: resData.data.totalPage,//总页数
                    current: num, //当前页码
                    pageSize: pageSize, //每页显示的条数
                    totalAmount: tempAmount  //尾行合计数据
                });

                if (resData.data.records.length === 0) {
                    Modal.info({
                        title: '提示',
                        content: '没有匹配的数据',
                    });
                }
            } else {
                console.log("请求数据错误：", resData.message);
            }
        });
    }

    //刷新列表
    refreshHandle = () => {
        this.selectedRowsObj = [];//清空选中的行数据
        this.pageNext();
    };

    pageNext(num, pageSize, conditonData, val) {
        if (val == 1) {
            console.log("aaaaa", this.props.searchComponentData)//配置条件
            console.log("bbbbbbb", conditonData)                //搜索条件
            // console.log("weishenme",this.props.searchComponentData[0].required)
            var a = this.props.searchComponentData
            var b = []
            var mark = 0
            for (var i in a) {//提取配置条件中required=1的object对象
                if (a[i].required == "1") {
                    b[i] = a[i];
                    //  break;
                }
            }

            console.log("b", b)
            if (b != undefined && b.length>0) {

                for (var i in b) {
                    console.log(b[i].name)
                    var min = b[i].name + "Min"
                    var max = b[i].name + "Max"
                    var base = b[i].name
                    //   console.log(min)
                    //  console.log(conditonData[min]   )//搜索条件对应名字的值（比对）

                    if (conditonData[min] == undefined && conditonData[max] == undefined && conditonData[base] == undefined) {
                        console.log("no")
                        Modal.error({
                            title: '请填写必填项',
                        });
                        mark = 1;
                        break
                    }
                }
            }
            console.log("mark", mark)
            if (mark == 0) {
                console.log("yes")
                this.setState({
                    loading: true
                });
                this.getListData(num, pageSize, conditonData);

            }
        } else {
            console.log("yes")
            this.setState({
                loading: true
            });
            this.getListData(num, pageSize, conditonData);

        }




        //         for(var i in a){//提取配置条件中required=1的object对象
        //             if(a[i].required=="1"){
        //                 b=a[i];
        //               //  break;
        //             }
        //         }
        //  console.log("b",b)
        //         if(b!=undefined){
        //         console.log("xx",b)
        //         console.log("xx",b.name)//等于1的名字
        //         var min=b.name+"Min"
        //         var max=b.name+"Max"
        //         console.log(min)
        //         console.log(conditonData[min]   )//搜索条件对应名字的值（比对）

        //         if(conditonData[min]==undefined&&conditonData[max]==undefined){
        //             console.log("no")
        //             Modal.error({
        //                 title: '请填写必填时间',
        //                // content: 'qing',
        //             });
        //         }else{
        //             console.log("yes")
        //             this.setState({
        //                 loading: true
        //             });
        //             this.getListData(num, pageSize, conditonData);

        //         }      
        //     }else{
        // console.log("yes")
        // this.setState({
        //     loading: true
        // });
        // this.getListData(num, pageSize, conditonData);

        // }  
    }

    hiddenBox() {
        let formBoxStyleMin = this.state.formBoxStyleMin;
        if (formBoxStyleMin == '') {
            formBoxStyleMin = 'formBoxStyleMin';
        } else {
            formBoxStyleMin = ''
        }
        this.setState({
            formBoxStyleMin: formBoxStyleMin
        })
    }


    componentDidUpdate() {
        //console.log("componentDidUpdate");
        // $(".hellor").parents(".fixedDataTableRowLayout_rowWrapper").addClass("addClassTotalTr");
    }

    componentDidMount() { //formbox高度
        // let height = window.getComputedStyle(this.refs.formBoxRef).height;
        // this.setState({
        //   formBoxStyleHeight:height
        // })

    }
    onPageChange = (pageNumber) => {
        this.pageNext(pageNumber);
        Actions.pageElementChange(); //创建监听，用来解决点击分页时把默认选中的数据去掉
        this.selectedRowsObj = [];//点击了分页，把当前选中的行数据清空
    };
    onShowSizeChange = (current, pageSize) => {
        this.pageNext(current, pageSize);
        Actions.pageElementChange();    //创建监听，用来解决点击分页时把默认选中的数据去掉
        this.selectedRowsObj = [];//点击了分页，把当前选中的行数据清空
    };

    render() {
        //当左侧隐藏时，列表宽度加上左侧的宽度，
        //1、当前this.props.isHideLeft 是从父组件listComponent传过来
        //2、this.props.isHideLeft 最顶级赋值是在页面 containers/Main/main.js
        let isHideLeft = this.props.isHideLeft;

        let formBoxStyleHeight = this.state.formBoxStyleHeight;
        let formBoxStyleMin = this.state.formBoxStyleMin;
        let divStyle = {};
        if (formBoxStyleMin) {
            divStyle = {
                //height: '33px',
                height: '0px',
                transition: 'all 0.5s linear',
                overflowY: 'auto',
                overflowX: 'hidden'
            };
        } else {
            divStyle = {
                //height: formBoxStyleHeight,
                height: '90px',
                transition: 'all 0.5s linear',
                overflowY: 'auto',
                overflowX: 'hidden'
            };
        }
        let headerOperation = this.props.headerOperation;
        return (
            <div className="wrap" style={{ fontSize: '12px' }}>
                {/*<div className={'formBoxStyle '+formBoxStyleMin} ref='formBoxRef'  >*/}
                {/*<div className='formTitle'>*/}
                {/*<span className='left'>查询条件</span>*/}
                {/*<span className='right'>*/}
                {/*<i className="slidUp" onClick={this.hiddenBox}></i>*/}
                {/*/!*<i className="slidDown"></i>*!/*/}
                {/*</span>*/}
                {/*</div>*/}
                {/*<div className="listSearch"  style={divStyle}>*/}
                {/*<WrappedAdvancedSearchForm*/}
                {/*formAlerSize='big'*/}
                {/*formUrl=""*/}
                {/*getFormData={this.props.searchComponentData}*/}
                {/*pageNext={this.pageNext}*/}
                {/*/>*/}
                {/*</div>*/}
                {/*</div>*/}
                <div className='formBoxStyle'>
                    <div className='formTitle'>
                        <span className='left'>{this.props.title ? this.props.title : "数据列表"}:</span>
                        <span className='right'>
                            {
                                headerOperation.map((e, index) => {
                                    let exOrImStyle = '';
                                    let showStyle = '';
                                    if (e.handleName == 'export' || e.handleName == 'import') {
                                        exOrImStyle = "exOrIm";
                                    }
                                    if (e.permission) {
                                        if(this.permissions && this.permissions.indexOf(e.permission) != -1){
                                            // console.log("有权限");
                                        }else{
                                            // console.log("没有权限");
                                            showStyle = "hidePerms";
                                        }
                                    }
                                    return (
                                        <a
                                            key={index}
                                            className={'mr-10 changeWordStyle tableAction ' + exOrImStyle + showStyle}
                                            onClick={this.rowHandles.bind(this, e.handleName)}
                                        >
                                            <Icon style={{ marginRight: '5px' }}
                                                type={e.iconClass ? e.iconClass : 'tags-o'} />
                                            {e.showName}
                                        </a>
                                    )
                                })
                            }

                        </span>
                    </div>
                    <FlexGrow
                        {...this.props}
                        ref='flexGrow'
                        className={this.state.showTotalAmount ? styles.totalAmount : ''}
                        loading={this.state.loading}
                        indexList={this.state.indexList}
                        pageNext={this.pageNext}
                        selectedRowsObjHandles={this.selectedRowsObjHandles}
                        totalAmount={this.state.totalAmount}
                        showTotalAmount={this.state.showTotalAmount}
                        unLoading={this.props.unLoading}
                    />

                    {/*<PageButton { ...this.state } pageNext={this.pageNext}/>*/}

                    <div className={styles.page}>
                        <Pagination
                            showSizeChanger
                            onShowSizeChange={this.onShowSizeChange}
                            showQuickJumper
                            defaultCurrent={1}
                            defaultPageSize={20}
                            total={this.state.totalCount}
                            onChange={this.onPageChange}
                            current={this.state.current}
                            pageSizeOptions={['10', '20', '40', '80']}
                        />
                        <span className={styles.totalCount}>共 {this.state.totalCount} 条</span>
                    </div>
                    {/* {this.state.order != null ? (
                        <div className={styles.tag}><Tag color="blue" style={{ fontSize: 17, cursor: 'text' }}> {this.state.order} </Tag></div>
                    ) : null} */}
                </div>
            </div>
        );
    }
}
